package com.opcode.costa.ui.menu.neworder;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.opcode.costa.R;
import com.opcode.nebulamobil.base.activities.FragmentActivityBase;
import com.opcode.nebulamobil.base.activities.MultiFragmentActivityBase;
import com.opcode.nebulamobil.base.components.LinearLayoutBase;
import com.opcode.nebulamobil.base.components.ListViewBase;
import com.opcode.nebulamobil.base.components.TextViewBase;
import com.opcode.nebulamobil.base.fragments.FragmentBase;
import com.opcode.nebulamobil.base.fragments.ResponsiveFragmentBase;
import com.opcode.nebulamobil.base.fragments.dialogfragments.RoundedProgressDialogBase;
import com.opcode.nebulamobil.base.interfaces.OnListViewBaseItemClickListener;
import com.opcode.nebulamobil.information.ApplicationInfo;
import com.opcode.nebulamobil.information.dataforms.costadataforms.PersonalDataForm;
import com.opcode.nebulamobil.information.dataforms.costadataforms.TableDataForm;
import com.opcode.nebulamobil.information.requests.costarequests.FoodListReq;
import com.opcode.nebulamobil.information.requests.costarequests.OrderRequest;
import com.opcode.nebulamobil.information.responses.costaresponses.FoodListResp;
import com.opcode.nebulamobil.information.responses.costaresponses.TableListResp;
import com.opcode.nebulamobil.utility.JsonConverter;
import com.opcode.nebulamobil.utility.ObjectCreator;
import com.opcode.nebulamobil.utility.UniqueIdCreator;


/**
 * Yeni sipariş girilebilmesi için yapilan masa seçim ekranıdır.
 * 
 * @author Okan ERDOĞAN 12 Haz 2014
 */
public class NewOrderStepOneFragment extends ResponsiveFragmentBase{

	private View vi;
	private ListViewBase tableNumberChoosingListview;
	private TableListAdapter tableListAdapter;
	private LinearLayoutBase afterLinearlayout, beforeLinearlayout,paperEffectLayout8;
	private TextViewBase tableNumberTextview;
	private ArrayList<TableDataForm> demoTableArray;
	private OrderRequest orderRequest;
	private RoundedProgressDialogBase roundedProgressDialogBase;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		this.vi = inflater.inflate(R.layout.new_order_step_one_fragment_layout,container, false);

		/*
		 * Yeni sipariş işleminin sonunda sunucuya orderRequestObject nesnesi
		 * gönderilecek. Bu nedenle bu işlemin ilk adımında sunucuya
		 * gönderilecek olan nesne oluşturuluyor ve bu nesnenin içerikleri her
		 * bir adımda dolduruluyor.
		 */
		this.orderRequest = new OrderRequest();
		/*
		 * Burada orderRequestObject nesnesinin personal info parametresi
		 * dolduruluyor. Bu parametre kullanıcının logini baaşarılı olması
		 * durumunda elde edildi. Personal Info verisi sürekli olarak static bir
		 * değişkende tutuluyor. Uygulamanın herhangi bir yerinde bu veriye
		 * erişilebilir.
		 */
		((FragmentActivityBase) getActivity()).createSharedPreferencesManager("sharedpreferences", getActivity());
		String personalDataFormAsJson = ((FragmentActivityBase) getActivity()).readFromSharedPreferences("personalDataForm", null);
		PersonalDataForm personalDataForm=(PersonalDataForm) JsonConverter.fromJsonString(personalDataFormAsJson,PersonalDataForm.class);
		this.orderRequest.setPersonalId(personalDataForm.getPersonelID());

		this.beforeLinearlayout = (LinearLayoutBase) this.vi.findViewById(R.id.table_choosing_before_linearlayout);
		this.afterLinearlayout = (LinearLayoutBase) this.vi.findViewById(R.id.table_choosing_after_linearlayout);
		this.paperEffectLayout8 = (LinearLayoutBase) this.vi.findViewById(R.id.paper_effect_layout_8);

		this.tableNumberTextview = (TextViewBase) this.vi.findViewById(R.id.table_number_textview);
		this.tableNumberChoosingListview = (ListViewBase) this.vi.findViewById(R.id.table_number_choosing_listview);

		TableListResp tableListResp = (TableListResp) getActivity().getIntent().getSerializableExtra("TableListResp");

		if (tableListResp != null) {
			this.demoTableArray = tableListResp.getTableList();
		}

		this.tableListAdapter = new TableListAdapter(this.getActivity(),R.layout.table_choosing_view, demoTableArray);
		this.tableNumberChoosingListview.setAdapter(tableListAdapter);

		this.tableNumberChoosingListview.setOnListViewBaseItemClickListener(new OnListViewBaseItemClickListener() {
			
			@Override
			public void onListViewItemClick(AdapterView<?> parent, View view,int position, long id) {
				/*
				 * Masa seçimi yapıldıktan sonra gösterilecek olan
				 * layout'a ilişkin düzenlemeler yapılıyor.
				 */
				tableNumberTextview.setText(""+ demoTableArray.get(position).getTableNumber());
				changeLayoutVisibility(beforeLinearlayout,afterLinearlayout, true);
				paperEffectLayout8.setVisibility(View.GONE);

				/*
				 * Burada seçili masa bilgisi request nesnemize set
				 * ediliyor.
				 */
				TableDataForm tableDataForm=demoTableArray.get(position);
				orderRequest.setTableId(tableDataForm.getTableId());

				/*
				 * Pipeline'da bir sonraki adıma geçilmek için aşağıdaki
				 * kod parçası çalıştırılıyor.
				 */
				createRequest();
			}
		});

		this.roundedProgressDialogBase=new RoundedProgressDialogBase();
		return this.vi;
	}

	
	
	
	public void onResume() {
		super.onResume();
		((MultiFragmentActivityBase) getActivity()).getPipelineManager().getStepList().get(0).setwFrag(new WeakReference<Fragment>(this));
		((MultiFragmentActivityBase) getActivity()).getPipelineManager().setActiveStep(((MultiFragmentActivityBase) getActivity()).getPipelineManager().getStepList().get(0));
		
	}

	
	/**
	 * 
	 */
	public void createRequest() {
		((FragmentActivityBase) getActivity()).showGeneralDialog(roundedProgressDialogBase, "NEW_ORDER_PROGRESS_DIALOG");

		ApplicationInfo.setResponseListener(this);
		FoodListReq foodListReq = new FoodListReq();
		foodListReq.setType("FoodListReq");
		foodListReq.setRequestId(UniqueIdCreator.createUniqueID());
		ApplicationInfo.getRequestListener().jsonRequestCame(JsonConverter.toJsonString(foodListReq));
	}

	/**
	 * Bu metodun geriye döndürdüğü۟ değer false ise bir önceki fragment'a
	 * geçilir. Eğer metodun geri dönüş değeri true ise aynı fragment içindeki
	 * bir önceki duruma (seçim yapılmamış durum) geçilir.
	 */
	public boolean backPressed() {
		if (beforeLinearlayout.getVisibility() == View.VISIBLE) {
			return false;
		} else if (afterLinearlayout.getVisibility() == View.VISIBLE) {
			changeLayoutVisibility(beforeLinearlayout, afterLinearlayout, false);
			paperEffectLayout8.setVisibility(View.VISIBLE);
			return true;
		}

		return false;

	}

	/**
	 * Bu sınıf parametre olarak verildiği ListView objesini düzenler.
	 * 
	 * @author Okan ERDOĞAN 30/05/2014
	 */
	class TableListAdapter extends ArrayAdapter<TableDataForm> {

		private Context context;
		private int resourceId;
		private ArrayList<TableDataForm> arrayList;

		public TableListAdapter(Context context, int textViewResourceId,ArrayList<TableDataForm> objects) {
			super(context, textViewResourceId, objects);

			this.context = context;
			this.resourceId = textViewResourceId;

			this.arrayList = objects;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = LayoutInflater.from(this.context).inflate(this.resourceId, null);
			}

			TableDataForm table = (TableDataForm) arrayList.get(position);

			TextViewBase tableNumber = (TextViewBase) convertView.findViewById(R.id.second_textview);
			tableNumber.setText("" + table.getTableNumber());
			return convertView;
		}

	}

	@Override
	public void responseCame(String response) {
		((FragmentActivityBase) getActivity()).closeGeneralDialog(roundedProgressDialogBase, "NEW_ORDER_PROGRESS_DIALOG");

		FoodListResp foodListResp = (FoodListResp) JsonConverter.fromJsonString(response, FoodListResp.class);
		((MultiFragmentActivityBase) getActivity()).pipelineForwardWithRequestObject(((MultiFragmentActivityBase) getActivity()).getPipelineManager(),
				(FragmentBase) ObjectCreator.createClass(NewOrderStepTwoFragment.class),orderRequest, foodListResp);
	}

}
